package com.yhsoft.common.service;

import com.yhsoft.common.utils.Md5Utils;
import com.yhsoft.flim.controller.request.MovieSeatLockInVo;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static java.lang.System.out;

/**
 * 以下参数是接口调用的必须参数：
 * 参数名	数值类型	参数值及说明
 * partnerId	Long	渠道 id
 * code	String	code
 * timestamp	Long	时间戳（13 位数据值，毫秒）30 秒有效时间
 * sign	String	签名
 * 其中签名的算法为：
 * <p>
 * string = partnerId + timestamp + code;
 * sign = Md5(string(转小写)+ secretKey);
 * <p>
 * <p>
 * 测试环境：
 * partnerId :   100219
 * code:            q80JSPZdmNPI
 * secretKey :   xcSjqJ9Ub4Tu
 * <p>
 * <p>
 * <p>
 * 使用httpclient工具类型同步数据
 */
public class FuSiLingFlimApiService {

    private static String testApi = "http://testopenapi.moviedata.fsiling.com";
    private static String testApi1 = "http://testopenapi.movie.fsiling.com";
    private static final CloseableHttpClient httpClient = HttpClients.createDefault();
    private static final String partnerId = "100219";
    private static final String code = "q80JSPZdmNPI";
    private static final String secretKey = "xcSjqJ9Ub4Tu";

    @NotNull
    private static HttpPost modifyCommPostHeader(List<BasicNameValuePair> nameValuePairs, String target) throws UnsupportedEncodingException {
        long timestamp = System.currentTimeMillis();
        String sign = Md5Utils.getMD5Code((partnerId + timestamp + code).toLowerCase() + secretKey).toLowerCase();

        out.println("请求地址： " + target);
        HttpPost httpPost = new HttpPost(target);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        nameValuePairs.add(new BasicNameValuePair("partnerId", partnerId));
        nameValuePairs.add(new BasicNameValuePair("code", code));
        nameValuePairs.add(new BasicNameValuePair("timestamp", String.valueOf(timestamp)));
        nameValuePairs.add(new BasicNameValuePair("sign", sign));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        return httpPost;
    }

    /**
     * 城市列表(建议一周同步一次)
     */
    public void cityList() throws IOException {
        String targetApi = testApi + "/openapi/city/list";
        // 无参
        HttpPost httpPost = modifyCommPostHeader(new ArrayList<>(), targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        System.out.println("response >>> : " + response);
        System.out.println(String.format("请求结果：%s", EntityUtils.toString(entity, StandardCharsets.UTF_8)));

        response.close();
    }

    /**
     * 热映影片列表接口(建议十二个小时同步一次)
     */
    public static String hostList() throws IOException {
        String targetApi = testApi + "/openapi/movie/hot/list";
        // 无参
        HttpPost httpPost = modifyCommPostHeader(new ArrayList<>(), targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }

    /**
     * 即将上映影片列表接口
     */
    public static String soonList() throws IOException {
        String targetApi = testApi + "/openapi/movie/soon/list";
        // 无参
        HttpPost httpPost = modifyCommPostHeader(new ArrayList<>(), targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }

    /**
     * 影院列表接口(建议一周同步一次)
     * pageNumber	否	int	分页（不传默认返回第一页数据），每页是500条数据
     */
    public static String cinemaList() throws IOException {
        String targetApi = testApi + "/openapi/cinema/list";
        List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("pageNumber", "100"));


        HttpPost httpPost = modifyCommPostHeader(new ArrayList<>(), targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }

    /**
     * 场次列表接口(建议一个小时同步一次)
     * cinemaId	是	Integer	影院ID
     * movieId	否	Integer	电影ID
     */
    public static String moviePlansList(String cinemaId, String movieId) throws IOException {
        String targetApi = testApi + "/openapi/movie/plans/list";
        List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("cinemaId", cinemaId));
        nameValuePairs.add(new BasicNameValuePair("movieId", movieId));

        HttpPost httpPost = modifyCommPostHeader(nameValuePairs, targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }

    /**
     * 座位图数据接口(实时调用)
     * showId	是	String	场次ID
     */
    public static String movieSeat(String showId) throws IOException {
        String targetApi = testApi1 + "/openapi/movie/seat/map";
        List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("showId", showId));

        HttpPost httpPost = modifyCommPostHeader(nameValuePairs, targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }

    /**
     * 座位图锁座接口
     * showId	是	String	场次ID
     * mobile	是	String	手机号码
     * seatNames	是	String	L排07座|L排08座
     * seatIds	是	String	672446|672447
     * totalMoney	否	Long	当前锁座电影票市场总额（单位分），传此参数则会强校验锁座调用方总金额是否福司令的锁座总金额是否一致，一致则锁座成功
     */
    public static String movieSeatLock(MovieSeatLockInVo inVo, String phoneNum) throws IOException {
        String targetApi = testApi1 + "/openapi/movie/seat/lock";

        List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("showId", inVo.getShowId()));
        nameValuePairs.add(new BasicNameValuePair("mobile", phoneNum));
        nameValuePairs.add(new BasicNameValuePair("seatNames", inVo.getSeatNames()));
        nameValuePairs.add(new BasicNameValuePair("seatIds", inVo.getSeatIds()));
        nameValuePairs.add(new BasicNameValuePair("totalMoney", inVo.getTotalMoney() + ""));

        HttpPost httpPost = modifyCommPostHeader(nameValuePairs, targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }

    /**
     * 座位图解锁接口
     * applyKey	是	String	锁座标识
     */
    public static String movieSeatUnLock(String applyKey) throws IOException {
        String targetApi = testApi1 + "/openapi/movie/seat/unlock";

        List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("applyKey", applyKey));

        HttpPost httpPost = modifyCommPostHeader(nameValuePairs, targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }

    /**
     * 支付确认接口（出票接口）
     * partnerOrderNo	是	String	合作商(接入方)订单号
     * applyKey	是	String	锁座标识
     * isChangeSeats	否	String	是否支持调座，true: 允许调座，不传或其他值表示不允许调座
     */
    public static String payConfirm(String partnerOrderNo, String applyKey, String isChangeSeats) throws IOException {
        String targetApi = testApi1 + "/openapi/movie/order/pay-confirm";

        List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("partnerOrderNo", partnerOrderNo));
        nameValuePairs.add(new BasicNameValuePair("applyKey", applyKey));
        nameValuePairs.add(new BasicNameValuePair("isChangeSeats", isChangeSeats));


        HttpPost httpPost = modifyCommPostHeader(nameValuePairs, targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }

    /**
     * 出票查询
     * partnerOrderCode	必须		String	合作商(接入方)订单号
     */
    public static String query(String orderId) throws IOException {
        String targetApi = testApi1 + "/openapi/movie/order/query";

        List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("partnerOrderCode", orderId));

        HttpPost httpPost = modifyCommPostHeader(nameValuePairs, targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }
}
